import extend from 'dva-model-extend';
import model from '@/baseModel';
import { getOne, getNodes, check, deleteNode } from '@/services/group';
import { getAll as getAllRoles } from '@/services/role';

const initState = {
  nodes: [],
  
  groups: [], // 部门
  roles: [], // 角色
  roleIds: [], // 已选择角色
  groupIds: [], // 勾选的部门
  groupPaths: [] // 勾选部门的path
}

export default extend(model, {
  namespace: 'group',
  state: {
    ...initState
  },
  effects: {
    *reset(_, { put }) {
      yield put({
        type: 'updateState',
        payload: {
          data: undefined
        },
      });
    },
    *resetNodes(_, { put }) {
      yield put({
        type: 'updateState',
        payload: {
          nodes: []
        },
      });
    },
    *fetchOne({ payload }, { call, put }) {
      const { data } = yield call(getOne, payload);
      const { roles = [], groupIds, ...rest } = data;
      yield put({
        type: 'updateState',
        payload: {
          data: rest,
          // roleIds: roles.map(_ => _.id),
          roleIds: roles,
          groupIds
        },
      });
    },
    *deleteNode({ payload }, { call, put }) {
      yield call(deleteNode, payload);
    },
    *valid({ payload }, { call }) {
      yield call(check, payload);
    },
    *fetchNodes({ payload }, { call, put }) {
      const { data } = yield call(getNodes, payload);
      yield put({
        type: 'updateState',
        payload: {
          nodes: data
        },
      });
    },
    *fetchRoles({ payload }, { call, put }) {
      const { data } = yield call(getAllRoles, payload);
      yield put({
        type: 'updateState',
        payload: {
          roles: data,
        },
      });
    },
    *fetchGroups({ payload }, { call, put }) {
      const { data } = yield call(getNodes, payload);
      yield put({
        type: 'updateState',
        payload: {
          groups: data,
        },
      });
    },
  },
});
